#include <stdio.h>
#include <signal.h>
#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <string.h>

#if 0
#define SIG_TEST 44

void signalFunction(int n, siginfo_t *info, void *unused) {
    printf("received value %d\n", info->si_int);
}

int  fd = open("/dev/YourModule", O_RDWR); 
if (fd < 0) return -1;

args.pid       = getpid();
ioctl(fd, IOCTL_SET_VARIABLES, &args); // send the our PID as argument

struct sigaction sig;

sig.sa_sigaction = signalFunction; // Callback function
sig.sa_flags = SA_SIGINFO;
sigaction(SIG_TEST, &sig, NULL);
#endif

#include <sys/param.h>
#include <sys/user.h>
#include <sys/sysctl.h>
#include <stdio.h>
#include <stdlib.h>

#if 0
int get_current_pid(int argc, char **argv)
{
  struct kinfo_proc *procs = NULL, *newprocs;
  char          thiscmd[MAXCOMLEN + 1];
  pid_t           thispid;
  int           mib[4];
  size_t                miblen;
  int           i, st, nprocs;
  size_t                size;
  
  
  size = 0;
  mib[0] = CTL_KERN;
  mib[1] = KERN_PROC;
  mib[2] = KERN_PROC_ALL;
  mib[3] = 0;
  miblen = 3;
  
  st = sysctl(mib, miblen, NULL, &size, NULL, 0);
  do {
    size += size / 10;
    newprocs = realloc(procs, size);
    if (newprocs == 0) {
      if (procs)
        free(procs);
      errx(1, "could not reallocate memory");
    }
    procs = newprocs;
    st = sysctl(mib, miblen, procs, &size, NULL, 0);
  } while (st == -1 && errno == ENOMEM);
  
  nprocs = size / sizeof(struct kinfo_proc);

  /* Now print out the data */
  for (i = 0; i < nprocs; i++) {
    thispid = procs[i].kp_proc.p_pid;
    strncpy(thiscmd, procs[i].kp_proc.p_comm, MAXCOMLEN);
    thiscmd[MAXCOMLEN] = '\0';
    printf("%d\t%s\n", thispid, thiscmd);
  }
  
  /* Clean up */
  free(procs);
  return(0);
}
#endif

void signalFunction(int n, siginfo_t *info, void *unused) 
{
    printf("received value %d\n", info->si_int);
}

#define LEN 128

void get_pid(void)
{
	char line[LEN];
	FILE *cmd = popen("pidof user_signal", "r");

	fgets(line, LEN, cmd);
	pid_t pid = strtoul(line, NULL, 10);
	printf("xxx pid = %d\n", pid);
	pclose(cmd);
}

#define BUF_SIZE 1024
void getPidByName(char* task_name)
{
    DIR *dir;
    struct dirent *ptr;
    FILE *fp;
    char filepath[50];//大小随意，能装下cmdline文件的路径即可
    char cur_task_name[50];//大小随意，能装下要识别的命令行文本即可
    char buf[BUF_SIZE];
    dir = opendir("/proc"); //打开路径
    if (NULL != dir)
    {
        while ((ptr = readdir(dir)) != NULL) //循环读取路径下的每一个文件/文件夹
        {
            //如果读取到的是"."或者".."则跳过，读取到的不是文件夹名字也跳过
            if ((strcmp(ptr->d_name, ".") == 0) || (strcmp(ptr->d_name, "..") == 0))             
				continue;
            if (DT_DIR != ptr->d_type) 
        		continue;

            sprintf(filepath, "/proc/%s/status", ptr->d_name);//生成要读取的文件的路径
            fp = fopen(filepath, "r");//打开文件
            if (NULL != fp)
            {
                if( fgets(buf, BUF_SIZE-1, fp)== NULL ){
            		fclose(fp);
            	continue;
       		}
        	sscanf(buf, "%*s %s", cur_task_name);

                //如果文件内容满足要求则打印路径的名字（即进程的PID）
                if (!strcmp(task_name, cur_task_name))
        			printf("PID:  %s\n", ptr->d_name);
                fclose(fp);
            }

        }
        closedir(dir);//关闭路径
    }
}
void getNameByPid(pid_t pid, char *task_name) {
    char proc_pid_path[BUF_SIZE];
    char buf[BUF_SIZE];
    sprintf(proc_pid_path, "/proc/%d/status", pid);
    FILE* fp = fopen(proc_pid_path, "r");
    if(NULL != fp){
        if( fgets(buf, BUF_SIZE-1, fp)== NULL ){
            fclose(fp);
        }
        fclose(fp);
        sscanf(buf, "%*s %s", task_name);
    }
}

void main2(int argc, char** argv)
{
    char task_name[50];
    pid_t pid = getpid();
    printf("pid of this process:%d\n", pid);
    getNameByPid(pid, task_name);

    /*
    strcpy(task_name, argv[0]+2);
    printf("task name is %s\n", task_name);
    getPidByName(task_name);
    */
    printf("task name is %s\n", task_name);
    getPidByName(task_name);
    sleep(15);
}

int main(int argc, char* argv[])
{
	int pid = 0;
	struct sigaction sig;
	#define SIG_TEST 44

	printf("poram name = %s\n", argv[0]);
	get_pid();
	pid = getpid();
	//get_current_pid(argc, argv);
	printf("pid = %d\n", pid);

	main2(argc, argv);

	sig.sa_sigaction = signalFunction; // Callback function
	sig.sa_flags = SA_SIGINFO;
	sigaction(SIG_TEST, &sig, NULL);

	while(1)
	{
		sleep(1);
	}
}
